#include "serverPool.h"
int exitPipe[2];
void handler(int signum){
    printf("signum =%d\n",signum);
    write(exitPipe[1],"1",1);
}
int IsLoading(int netfd){
    if(send(netfd, "请输入用户名和密码", sizeof("请输入用户名和密码"), 0) <= 0){
        printf("error recv loadmsg\n");
        return -1;
    }
    char load[2][32];
    char *username = load[0];
    if(recv(netfd, load, 2 * 32, 0) <= 0){
        printf("error recv loadmsg\n");
        return -1;
    }

    struct spwd *info = getspnam(username);
    if(info == NULL){
        return -1;
    }
    int i = strlen(info->sp_pwdp) - 1;

    for(; i >= 0; --i){
        if(info->sp_pwdp[i] == '$'){
            break;
        }
    }
    char *salt = (char *)malloc(i);
    strncpy(salt, info->sp_pwdp, i);
    salt[i] = '\0';
    char *password = crypt(load[1], salt);
    printf("%s\n%s\n", salt, password);
    if(strcmp(info->sp_pwdp, password) == 0){
        openlog("Server", LOG_PID | LOG_PERROR, LOG_USER);
        //syslog(LOG_ERR, "错误信息");
        //syslog(LOG_WORNING, "错误信息");
        return 0;
    }else{
        return -1;
    }
}
/* Usage:  */
int main(int argc, char *argv[]){                                  
    ARGS_CHECK(argc,4);

    pipe(exitPipe);
    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("老登儿退出！\n");
        exit(0);
    }
    close(exitPipe[1]);
    int workerNum=atoi(argv[3]);
    serverPool_t serverPool;
    serverPoolInit(&serverPool,workerNum);
    makeWorker(&serverPool);

    //tcp
    int sockfd=initTcp(argv[1],argv[2]);
    printf("服务端正常启动！\n");
    //epoll
    int epfd=epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);
    struct epoll_event readySet[1024];
    while(1){
        int readNum=epoll_wait(epfd,readySet,1024,-1);
        for(int i=0;i<readNum;i++){
            int rdsfd=readySet[i].data.fd;
            if(rdsfd==sockfd){
                int netfd=accept(sockfd,NULL,NULL);
                if(IsLoading(netfd) == -1){
                    close(netfd);
                    continue;
                }
                send(netfd, "welcome", sizeof("welcome"), 0);
                printf("工人已连接netfd=%d\n",netfd);
                pthread_mutex_lock(&serverPool.mutex);
                printf("主人得到了一个netfd=%d\n",netfd);
                enQueue(&serverPool.que,netfd);
                pthread_cond_broadcast(&serverPool.cond);
                pthread_mutex_unlock(&serverPool.mutex);
            }else if(rdsfd==exitPipe[0]){
                printf("退出线程池！\n");
                pthread_mutex_lock(&serverPool.mutex);
                serverPool.exitFlag=1;
                pthread_cond_broadcast(&serverPool.cond);
                pthread_mutex_unlock(&serverPool.mutex);
                for(int j=0;j<workerNum;j++){
                    pthread_join(serverPool.tidArr.id[j],NULL);
                }
                printf("主人退出！\n");
                exit(0);
            }
        }
    }

    return 0;
}

